package tool.encode

import androidx.compose.runtime.Composable
import kotlinx.coroutines.runBlocking
import org.jetbrains.compose.resources.getString
import tool.Tool
import tool.ToolEvent
import top.mcwebsite.devtoolbox.devtoolbox.generated.resources.Res
import top.mcwebsite.devtoolbox.devtoolbox.generated.resources.base64_decode
import top.mcwebsite.devtoolbox.devtoolbox.generated.resources.base64_encode
import java.util.Base64

object Base64EncodeTool : Tool {

    private val _name: String by lazy {
        runBlocking {
            getString(Res.string.base64_encode)
        }
    }

    override fun getName(): String {
        return _name
    }

    @Composable
    override fun Render(onEvent: (ToolEvent) -> Unit) {
        val base64Encoder = Base64.getEncoder()
        EncodeAndDecodeToolUI(
            getName(),
            onBackClick = { onEvent(ToolEvent.BackEvent) },
        ) {
            val data = it.toByteArray(Charsets.UTF_8)
            base64Encoder.encodeToString(data)
        }
    }

}

object Base64DecodeTool : Tool {

    private val _name: String by lazy {
        runBlocking {
            getString(Res.string.base64_decode)
        }
    }

    override fun getName(): String {
        return _name
    }

    @Composable
    override fun Render(onEvent: (ToolEvent) -> Unit) {
        val base64Decoder = Base64.getDecoder()
        EncodeAndDecodeToolUI(
            getName(),
            onBackClick = { onEvent(ToolEvent.BackEvent) },
        ) {
            kotlin.runCatching {
                base64Decoder.decode(it).toString(Charsets.UTF_8)
            }.getOrDefault("")
        }
    }

}